package com.rn.gypsophila.rabbitmq.config;

import com.rn.gypsophila.rabbitmq.AbstractRabbitmqConfig;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Description: RabbitMQ配置
 *
 * @author 然诺
 * @date 2019/08/07
 */
@Configuration
public class RabbitmqConfig extends AbstractRabbitmqConfig {

    public static final String BIZ_QUEUE = "biz.queue";
    public static final String BIZ_EXCHANGE = "biz.exchange";
    public static final String BIZ_ROUTING_KEY = "biz.routing.key";

    public static final String DEAD_LETTER_QUEUE = "dead.letter.queue";
    public static final String DEAD_LETTER_EXCHANGE = "dead.letter.exchange";
    public static final String DEAD_LETTER_ROUTING_KEY = "dead.letter.routing.key";

    /**
     * 下单业务队列
     */
    @Bean("bizQueue")
    public Queue bizQueue() {
        Map<String, Object> args = new HashMap<>(2);
        args.put("x-dead-letter-exchange", DEAD_LETTER_EXCHANGE);
        args.put("x-dead-letter-routing-key", DEAD_LETTER_ROUTING_KEY);
        // 队列设置成持久化
        return QueueBuilder.durable(BIZ_QUEUE).withArguments(args).build();
    }

    /**
     * 死信队列
     */
    @Bean("deadLetterQueue")
    public Queue deadLetterQueue() {
        return QueueBuilder.durable(DEAD_LETTER_QUEUE).build();
    }

    /**
     * 下单业务交换机
     */
    @Bean("bizExchange")
    public DirectExchange bizExchange() {
        // 交换机设置成持久化
        return (DirectExchange) ExchangeBuilder.directExchange(BIZ_EXCHANGE).durable(true).build();
    }

    /**
     * 死信交换机
     */
    @Bean("deadLetterExchange")
    public DirectExchange deadLetterExchange() {
        return (DirectExchange) ExchangeBuilder.directExchange(DEAD_LETTER_EXCHANGE).build();
    }

    /**
     * 订单队列与交换机绑定
     */
    @Bean
    Binding bizBinding(@Qualifier("bizQueue") Queue queue,
                         @Qualifier("bizExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(BIZ_ROUTING_KEY);
    }

    /**
     * 死信队列与交换机绑定
     */
    @Bean
    Binding deadLetterBinding(@Qualifier("deadLetterQueue") Queue queue,
                              @Qualifier("deadLetterExchange") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_ROUTING_KEY);
    }
}
